package com.qolome.configuration;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.DynamicTableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Qolome
 * @version V1.0
 * @Description MyBatisPlus配置
 * @date 2020年 01月12日 16:27:28
 */
@Configuration
public class MyBatisPlusConfiguration {

    public  static ThreadLocal<String> myTableName  = new ThreadLocal<>();



    /**
     * 乐观锁插件
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor paginationInterceptor  = new PaginationInterceptor();


        ArrayList<ISqlParser> iSqlParserList = new ArrayList<> ();
         /* //增加多租户
        TenantSqlParser tenantSqlParser = new TenantSqlParser ();
        tenantSqlParser.setTenantHandler (new TenantHandler () {
            @Override
            public Expression getTenantId (boolean where) {
                return new LongValue (1216293266584178689L);
            }

            @Override
            public String getTenantIdColumn () {
                return "manager_id";
            }

            @Override
            public boolean doTableFilter (String tableName) {
                //不加多租户过滤
                if("role".equals (tableName)){
                    return true;
                }
                return false;
            }
        });
        iSqlParserList.add (tenantSqlParser);
        paginationInterceptor.setSqlParserList (iSqlParserList);*/

         // 动态表名
        DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser ();
        Map<String, ITableNameHandler> stringTableNameHandlerMap = new HashMap<> ();

        stringTableNameHandlerMap.put (
                "user",(metaObject,sql,tableName)->myTableName.get ());
        dynamicTableNameParser.setTableNameHandlerMap (stringTableNameHandlerMap);

        iSqlParserList.add (dynamicTableNameParser);
        paginationInterceptor.setSqlParserList (iSqlParserList);

        myTableName.remove ();

       /* //过滤不增加租户信息

        paginationInterceptor.setSqlParserFilter((metaObject)->{

            MappedStatement mappedStatement = SqlParserHelper.getMappedStatement (metaObject);
           if("com.qolome.dao.mapper.UserMapper.selectById".equals (mappedStatement.getId ())){
               return true;
           }
            return false;
        });*/


        return paginationInterceptor;
    }
}
